<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 查找院系 -->
            <el-input
              placeholder="请输入查找内容"
              v-model="queryInfo.query"
              class="input-with-select"
              clearable
              @clear="clearInput"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="searchClass()"
              >
              </el-button>
            </el-input>
        </el-col>
        <!-- 添加院系模块 -->
            <el-col :span="16">
            <div class="right">
                <el-button type="success" @click="excelShow" plain>
                  导出Excel表格
                </el-button>
                <el-button type="success" plain @click="excelImport">
                  批量导入
                </el-button>
                <el-button type="primary" @click="addClass">
                  添加班级
                </el-button>
            </div>
            <el-dialog
              title="添加班级"
              :visible.sync=  "dialogVisible"
              width="50%">
              <el-form :label-position="labelPosition" label-width="80px" :model="classForm">
                <el-form-item label="班级名称:" prop="name">
                  <el-input v-model="classForm.name" placeholder="请输入班级名"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">              
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirm">确 定</el-button>
                </span>
            </el-dialog>
          </el-col>
        </el-row>
        <!-- 展示该院系所有班级 -->
            <el-table
            :data="Class"
            style="width: 100%; top: 20px">
              <el-table-column
                fixed
                prop="id"
                label="id"
                >
              </el-table-column>
              <el-table-column
                prop="name"
                label="班级"
                >
              </el-table-column>
              <el-table-column
                prop="deptInfo.univInfo.schoolName"
                label="所属高校"
                >
              </el-table-column>
              <el-table-column
                prop="deptInfo.name"
                label="所属院系"
                >
              </el-table-column>
              <el-table-column
                prop="createTime"
                label="创建时间"
                >
              </el-table-column>
              <el-table-column
                prop="modiTime"
                label="编辑时间"
                >
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                >
                <template slot-scope="scope">
                  <el-button @click="edit(scope.row)" type="text" icon="el-icon-edit" size="small">编辑</el-button>
                  <el-button @click="deleteClassById(scope.row.id)" type="text" style="color: #fa6962" icon="el-icon-delete" size="small">删除</el-button>
                </template>
              </el-table-column>      
            </el-table>
      <!-- 分页 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pageNum"
      :page-sizes="[5, 10, 15]"
      :page-size="queryInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
import{ getClass,searchClassByName,addClass,updateClass,deleteClass, exportExcel} from '#/OrganizationManagement/class.js'
import { addLogs } from '#/Home/Home.js'

export default {
  name: 'Class',
  meta: {
    title: '班级管理'
  },
  data() {
    return {
      queryInfo: {
        //查询的内容       
        query: "",
        // 当前页数     
        pageNum: 1,     
        // 每页显示多少数据   
        pageSize: 5
        }, 
        Class:[],
        select:"",
        //总数据条数
        total: 0,
        //添加企业弹窗
        dialogVisible:false,
        updateFlag:false,
        labelPosition: 'right',
        classForm: {
          name:''
        },
        excelImportShow:false,
        id:''
    };
  },
  created() {
    this.id = this.$route.query.id;
    this.getClasses()
  },
  methods: {
    // 所有机构（班级）信息
    async getClasses() {
      await getClass(this.id,this.queryInfo.pageNum,this.queryInfo.pageSize).then(res => { 
        const result = res.data
        console.log(result)
        if(result.ret === 0) {
          this.Class = result.orgs.class.content
          this.total = result.orgs.class.totalElements
        }else{
          this.$message.error('服务器请求错误！');
        }
      })
    },
    confirm(){
      if(this.addFlag){
        this.classForm.deptId = this.$route.query.id;
        addClass(this.classForm).then(res => {
          if(res.data.ret == 0){
            this.$message.success("添加成功");
            this.dialogVisible = false;
            addLogs({
              userId: window.sessionStorage.getItem('userId'),
              behavior: '添加了新的班级信息',
            })
          }
          this.getClasses();
        });
      }else{
        updateClass(this.classForm.id,this.classForm).then(res => {
          console.log(res.data.classId)
          if(res.data.ret == 0){
            this.$message.success("修改成功");
            this.dialogVisible = false;
            addLogs({
              userId: window.sessionStorage.getItem('userId'),
              behavior: '修改了班级信息',
            })
          }
          this.getClasses();
        });
      }
    },
    clearInput() {
      this.queryInfo.pageNum = 1;
      this.queryInfo.pageSize = 5;
      this.getClasses();
    },
    addClass() {
      this.addFlag = true;
      this.classForm = {
        name:'',
      }
      this.dialogVisible = true;
    },
    edit(obj){  
      this.addFlag = false;
      Object.assign(this.classForm, obj);
      this.dialogVisible = true;
    },
    //通过班级名搜索班级
    async searchClass() {
      if(!this.queryInfo.query) {
        return this.$message.error('请输入名称')
      }
      this.queryInfo.pageNum = 1;
      // console.log(111)
      await searchClassByName(this.queryInfo).then(res => {
        if(res.status === 200) {
          console.log(res.data.orgs)
          this.Class = res.data.orgs.class.content
          this.total = res.data.orgs.class.totalElements
          if(this.Class === []) {
            this.$message.info('搜索结果为空')
          } else {
            this.$message.success('搜索成功！')
          }
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    //通过id删除班级信息
    deleteClassById(id) {
      this.$confirm(
        "此操作将永久删除该班级, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(confirmResult => {
        if(confirmResult === 'confirm') {
          deleteClass(id).then(res =>{
            console.log(res)
            if(res.data.ret == 0) {
              this.$message.success("删除成功！")
              addLogs({
                  userId: window.sessionStorage.getItem('userId'),
                  behavior: '成功删除了班级',
                })
            }
            this.getClasses();
          })
        }
      }).catch((err) => err);
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getClasses();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getClasses();
    },
    async excelShow() {
      await exportExcel().then(res => {
        if(res.status === 200) {
          const blob = new Blob([res.data], {  // res 为后台返回数据
            type: 'application/vnd.ms-excel;charset=utf-8', // 导出数据生成excel的格式设置
          });
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a');
            elink.download = `班级信息.xlsx`;
            elink.style.display = 'none';
            elink.target = '_blank';
            elink.href = window.URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
          }
        }
      })
    },
    excelImport() {}
  }
};
</script>
<style scoped>
  .right {
    float: right;
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
</style>

